package ltd.hxya.novel.admin.service.impl;

import ltd.hxya.novel.admin.entity.User;
import ltd.hxya.novel.admin.mapper.UserMapper;
import ltd.hxya.novel.admin.service.IUserService;
import ltd.hxya.novel.springsecurity.entity.UserDetail;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class LoginUserServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询数据库，判断登录是否正确
        User user = userService.getUserByUsername(username);


        List<String> permissions = userMapper.getPermissionsByUserId(user.getUserId());
        UserDetail userDetail = new UserDetail(permissions);
        //TODO 对该部分的写法进行优化
        ltd.hxya.novel.springsecurity.entity.User user1 = new ltd.hxya.novel.springsecurity.entity.User();
        BeanUtils.copyProperties(user,user1);
        userDetail.setUser(user1);
        return userDetail;
    }
}
